package com.appengine.paranoid_android.lost;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LockScreen extends Activity implements LockScreenMonitor.LockScreen {
  private static final boolean DEBUG = true;
  private static final String TAG = "Info.LockScreen";

  KeyguardManager mKeyguardManager;
  KeyguardLock mKeyguardLock;

  TelephonyManager mTelephonyManager;

  LockScreenMonitor mMonitor;

  FrameLayout mFrame;
  LinearLayout mContent;

  private TextView mHeaderSim1;
  private TextView mHeaderSim2;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
    requestWindowFeature(Window.FEATURE_PROGRESS);

    mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    mMonitor = new LockScreenMonitor(this, this);

    mContent = new LinearLayout(this) {
      @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
        return LockScreen.this.onKeyDown(keyCode, event);
      }

      @Override
      protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        if (DEBUG) Log.d(TAG, "Focus changed: " + gainFocus + " " + direction + " " + previouslyFocusedRect);
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
      }

      @Override
      public void onWindowFocusChanged(boolean hasWindowFocus) {
        if (DEBUG) Log.d(TAG, "Window focus changed: " + hasWindowFocus);
        super.onWindowFocusChanged(hasWindowFocus);
      }

      @Override
      protected void onWindowVisibilityChanged(int visibility) {
        if (DEBUG) Log.d(TAG, "Window visibility changed: " + visibility);
        super.onWindowVisibilityChanged(visibility);
      }

    };
    mContent.setId(0);
    getLayoutInflater().inflate(R.layout.lock_screen, mContent, true);
    mContent.setFocusable(true);
    mContent.setFocusableInTouchMode(true);
    mContent.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

    mFrame = new FrameLayout(this);
    mFrame.addView(mContent);
    final int stretch = ViewGroup.LayoutParams.FILL_PARENT;
    int flags = WindowManager.LayoutParams.FLAG_DITHER
            | WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
//            | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
            stretch, stretch, WindowManager.LayoutParams.TYPE_KEYGUARD,
            flags, PixelFormat.OPAQUE);
    lp.setTitle("Keyguard");
    setContentView(mFrame, lp);

    mHeaderSim1 = (TextView) findViewById(R.id.headerSimOk1);
    mHeaderSim2 = (TextView) findViewById(R.id.headerSimOk2);
  }

  @Override
  public void onResume() {
    super.onResume();
    if (DEBUG) Log.d(TAG, "Resumed: keyguardRestricted: " + mKeyguardManager.inKeyguardRestrictedInputMode());
    InfoService.lockScreenShowing = true;
    InfoService.exitingLockScreen = false;
    updateNetworkInformation();
    if (mKeyguardLock == null) {
      mMonitor.registerReceiver();
      mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG);
      mKeyguardLock.disableKeyguard();
      if (DEBUG) Log.d(TAG, "Disabled keyguard.");
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    if (InfoService.exitingLockScreen) {
      exitScreen();
    }
    if (DEBUG) Log.d(TAG, "Paused: keyguardRestricted: " + mKeyguardManager.inKeyguardRestrictedInputMode());
  }

  @Override
  public void onStop() {
    if (DEBUG) Log.d(TAG, "Stopping: keyguardRestricted: " + mKeyguardManager.inKeyguardRestrictedInputMode());
    super.onStop();
    if (InfoService.lockScreenShowing) {
      exitScreen();
    }
    if (DEBUG) Log.d(TAG, "Stopped: keyguardRestricted: " + mKeyguardManager.inKeyguardRestrictedInputMode());
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (DEBUG) Log.d(TAG, "Key down: " + event + ", restricted: " + mKeyguardManager.inKeyguardRestrictedInputMode());
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
//      finish();
//      if (keyCode == KeyEvent.KEYCODE_MENU) {
//        mKeyguardManager.exitKeyguardSecurely(null);
//      }
    } else if (keyCode == KeyEvent.KEYCODE_HOME) {
      InfoService.exitingLockScreen = true;
    }
    return true;
  }

  @Override
  public void onWindowFocusChanged(boolean hasWindowFocus) {
    // The only notification we get that the unlock screen has been displayed is that we lose focus. When that happens
    // hide the content, so that the flicker after unlock is less obvious.
    mFrame.setVisibility(hasWindowFocus ? View.VISIBLE : View.GONE);
    if (DEBUG) Log.d(TAG, "Window focus changed: " + hasWindowFocus);
  }

  private void exitScreen() {
    if (!mKeyguardManager.inKeyguardRestrictedInputMode()) {
      finish();
    }
    if (mKeyguardLock != null) {
      mKeyguardLock.reenableKeyguard();
      mKeyguardLock = null;
      if (DEBUG) Log.d(TAG, "Reenabled keyguard.");
      mMonitor.unregisterReceiver();
    }
    InfoService.lockScreenShowing = false;
  }

  // Set the network operator name.
  protected void updateNetworkInformation() {
    if (mTelephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
      String network = mTelephonyManager.getNetworkOperatorName();
      if (network == null) {
        network = mTelephonyManager.getSimOperatorName();
      }
      mHeaderSim1.setVisibility(View.VISIBLE);
      mHeaderSim1.setText(network);
      mHeaderSim2.setVisibility(View.GONE);
    } else {
      // Not worth keeping track and most information is not available anyway.
      mHeaderSim1.setVisibility(View.GONE);
      mHeaderSim2.setVisibility(View.VISIBLE);
      mHeaderSim2.setText("XXX Press back for information");
    }
  }

  @Override
  public void onBatteryUpdate(int pluggedInStatus, int batteryLevel) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onConfigurationChange() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onTimeUpdate() {
    // TODO Auto-generated method stub

  }
}
